package example.hellosecurity.filter;

import example.hellosecurity.session.LoginAccountModel;
import example.hellosecurity.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

/**
 * Jwt认证过滤器
 * 继承OncePerRequestFilter可以保证每次请求只通过一次过滤器
 *
 * @author ：FuXx
 * @className : example.hellosecurity.filter.JwtAuthenticationFilter
 * @since ：2024/8/19
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("X-Authorization");
        System.out.println("请求地址：" + request.getServletPath());
        try {
            Claims claims = JwtUtil.parseJwt(token, JwtUtil.SIGNING_KEY);
            Integer id = claims.get("id", Integer.class);
            String name = claims.get("name", String.class);
            LoginAccountModel model = new LoginAccountModel();
            model.setName(name);
            model.setId(id);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(model, "", Collections.emptyList());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (Exception e) {
            SecurityContextHolder.clearContext();
        }
        filterChain.doFilter(request, response);
    }
}
